<!-- 加油首页 -->
<template>
  <view class="bigbox">
    <view class="top">
      <!-- 搜索框 -->
      <view class="bjbox">
        <view class="search-container">
          <u-search
            v-model="searchKey"
            placeholder="搜索加油站"
            @input="handleSearch"
            :show-action="false"
          />
        </view>
        <view class="reload-icon">
          <u-icon name="reload" size="40" @click="getStoreList"></u-icon>
        </view>
      </view>
      <!-- 背景 -->
      <view
        style="border-radius: 40rpx; overflow: hidden; margin-bottom: 20rpx"
      >
        <u-image
          :src="sygg"
 
          height="220rpx"
          style="padding: 0 20rpx"
        ></u-image>
      </view>
      <!-- 筛选 -->
      <view class="sxbox">
        <view
          class="kuai"
          @click="handleOliDistance"
          style="margin: 0 20rpx"
          :class="{ active: active == 1 }"
        >
          距离优先
        </view>
        <view
          class="kuai"
          @click="handleOliPrice"
          :class="{ active: active == 2 }"
        >
          价格优先
        </view>
        <view class="dropdown">
          <van-dropdown-menu
            active-color="#ff6c18"
            :class="{ active: active === 3 }"
            style="box-shadow: none"
          >
            <van-dropdown-item
              @change="handleDropdownOli"
              v-model="oliId"
              :options="oliList"
            />
            <van-dropdown-item
              @change="handleDropdownbrand"
              v-model="brand"
              :options="brandList"
            />
          </van-dropdown-menu>
        </view>
      </view>
    </view>
    <u-loadmore
      style="margin-top: 50rpx"
      status="loading"
      v-if="showSkeleton"
    />
    <!-- 列表 -->
    <view class="footer">
      <template v-if="!showSkeleton && goodsList.length > 0">
        <view class="xhz" v-for="ele in goodsList" @click="handleGoBuy(ele)">
          <view class="xhz-l">
            <view class="head">
              <view style="display: flex">
                <van-image
                  style="margin-right: 20rpx"
                  width="50rpx"
                  height="50rpx"
                  :src="ele.logo"
                  fit="contain"
                />
                <view class="btwz overwz">{{ ele.stationName }}</view>
              </view>
              <view>
                <u-button
                  type="primary"
                  shape="circle"
                  style="width: 140rpx; height: 60rpx; font-size: 28rpx"
                  @click="handleGoBuy(ele)"
                >
                  去加油
                </u-button>
              </view>
            </view>
            <view class="textBox">
              <view class="left">
                <view class="address-text">
                  {{ ele.address }}
                </view>
              </view>
              <view class="right" @click.stop="gotoAddress(ele)">
                <text>{{ getDistance(ele.distance) }}</text>
                <text style="margin: 0 10rpx">|</text>
                <text style="color: #fd6135">
                  <van-icon name="guide-o" color="#fd6135" size="15px" />导航
                </text>
              </view>
            </view>

            <view class="jgwz" style="margin-left: 60rpx">
              <span style="font-size: 34rpx">￥{{ ele.minPrice }}</span>
              <span style="font-size: 22rpx">/L起</span>
              <view style="display: inline-block" v-if="ele.hasPromotion">
                <text class="quan1">券</text>
                <text class="quan2">{{ ele.promotionInfo }}</text></view
              >
            </view>
          </view>
        </view>
         <!-- 上拉加载更多提示 -->
         <u-loadmore 
          :status="loadStatus" 
          :load-text="loadText"
          v-if="!showSkeleton"
        />
        <!-- 返回顶部按钮 -->
        <u-back-top :scroll-top="scrollTop"></u-back-top>
      </template>
      <view v-else-if="!showSkeleton && goodsList.length === 0">
        <van-empty description="暂无内容" />
      </view>
    </view>
  </view>

  <!-- 地图弹出框 -->
  <van-popup
    v-model:show="showMap"
    round
    position="bottom"
    :style="{ height: '30%' }"
  >
    <view class="mapbox">
      <van-button class="btn" @click="openGMap" type="default"
        >高德地图</van-button
      >
      <van-button class="btn" @click="openBMap" type="default"
        >百度地图</van-button
      >
      <van-button class="btn" @click="openTMap" type="default"
        >腾讯地图</van-button
      >
      <van-button class="btn" @click="copyMap" type="default"
        >复制地址</van-button
      >
      <van-button class="btn btn2" type="default" @click="showMap = false"
        >取消</van-button
      >
    </view>
  </van-popup>
</template>
<script setup lang="ts">
import { ref, computed, reactive, watch } from 'vue'
import { onLoad, onReady, onPageScroll,onReachBottom  } from '@dcloudio/uni-app'
// api
import { productApi, baseApi } from '@/api'
//工具
import { getLocationInfo } from '@/utils/location'
import { useOilStore } from '@/store'
import sygg from './static/sygg2.png'
// 初始化数据
const isApp = ref(false)
const showSkeleton = ref(true)
const oilStore = useOilStore()
// 1=按距离排序，2=按价格排序
const sortType = ref(1)
const active = ref(1)
//地图展示
const showMap = ref(false)
const searchKey = ref('')
const scrollTop = ref(0)
const oliId = ref(2) //油型
const oliList = ref()
const brand = ref(0) //品牌
const brandList = ref()
const location = ref()
// 分页
const paramsList = reactive({
  pageNum: 1,
  pageSize: 10
})
const clickObj = ref<any>({})
// 油站列表
const goodsList = ref<any>([])
// 添加相关响应式变量
const pullDownRefresh = ref()
const loadStatus = ref('loadmore') // loadmore, loading, nomore
const total = ref(0) // 总数据量

// 下拉刷新文本
const pullDownText = reactive({
  refreshing: '正在刷新...',
  refreshSuccess: '刷新成功',
  refreshFail: '刷新失败'
})

// 上拉加载文本
const loadText = reactive({
  loadmore: '上拉加载更多',
  loading: '正在加载...',
  nomore: '没有更多了'
})

// #region ************************* 筛选操作 *********/

// 获取枚举列表
const enumOliList = async () => {
  const { data } = await baseApi.getBASE_DictEnum({
    parentValue: 'sys_oil_dict',
    noPaging: true
  })
  if (data && data.length > 0) {
    oliList.value = data.map((item: any) => {
      return {
        text: item.name,
        value: Number(item.value)
      }
    })
    oliId.value = oliList.value[0].value
  } else {
    oliList.value = []
  }
}
const enumBrandList = async () => {
  const { data } = await baseApi.getBASE_DictEnum({
    parentValue: 'sys_oil_brand_dict',
    noPaging: true
  })
  if (data && data.length > 0) {
    brandList.value = data.map((item: any) => {
      return {
        text: item.name,
        value: Number(item.value)
      }
    })
    brand.value = brandList.value[0].value
  } else {
    brandList.value = []
  }
}

/// 距离优先
const handleOliDistance = () => {
  active.value = 1
  sortType.value = 1
  getStoreList(false) // 重置为第一页
}

// 价格优先
const handleOliPrice = () => {
  active.value = 2
  sortType.value = 2
  getStoreList(false) // 重置为第一页
}

// 油型筛选
const handleDropdownOli = (e: any) => {
  oliId.value = e
  getStoreList(false) // 重置为第一页
}

// 品牌筛选
const handleDropdownbrand = (e: any) => {
  brand.value = e
  getStoreList(false) // 重置为第一页
}

// 搜索
const handleSearch = (e: any) => {
  searchKey.value = e
  getStoreList(false) // 重置为第一页
}

//#endregion

//  #region ************************* 获取加油站列表 *********   ***********/ 
 

// 修改 getStoreList 函数
const getStoreList = async (isLoadMore = false) => {
  try {
    if (!isLoadMore) {
      // 首次加载或刷新
      paramsList.pageNum = 1
      showSkeleton.value = true
      goodsList.value = []
    } else {
      // 加载更多
      // 检查是否已经加载完所有数据
      if (goodsList.value.length >= total.value) {
        loadStatus.value = 'nomore'
        return
      }
      paramsList.pageNum++
    }
    
    loadStatus.value = 'loading'
    
    const { data, code } = await productApi.getStoreList({
      ...location.value,
      pageNum: paramsList.pageNum,
      pageSize: paramsList.pageSize,
      stationName: searchKey.value,
      sortType: sortType.value,
      oliId: oliId.value,
      brand: brand.value
    })
    
    if (code === 200) {
      // 更新总数据量
      total.value = data.total || 0
      
      let newList = []
      if (data.list && data.list.length > 0) {
        newList = data.list.filter((item: any) => {
          return item.hasPromotion
        })
      }
      
      if (isLoadMore) {
        // 加载更多数据
        goodsList.value = [...goodsList.value, ...newList]
        // 根据是否有新数据来决定加载状态
        loadStatus.value = newList.length < paramsList.pageSize ? 'nomore' : 'loadmore'
      } else {
        // 首次加载或刷新
        goodsList.value = newList
        // 根据是否有数据来决定加载状态
        loadStatus.value = newList.length < paramsList.pageSize ? 'nomore' : 'loadmore'
      }
      
      // 特别处理：如果返回空数组，设置为没有更多数据
      if (newList.length === 0 && !isLoadMore) {
        loadStatus.value = 'nomore'
      }
    } else {
      if (!isLoadMore) {
        goodsList.value = []
      }
      loadStatus.value = 'nomore' // 接口返回错误时也设置为没有更多
    }
  } catch (error: any) {
    console.log(error)
    uni.showToast({
      title: error.msg || '加载失败',
      icon: 'error'
    })
    if (!isLoadMore) {
      goodsList.value = []
    }
    loadStatus.value = 'nomore'
  } finally {
    showSkeleton.value = false
    // 完成下拉刷新
    if (!isLoadMore && pullDownRefresh.value) {
      pullDownRefresh.value.complete()
    }
  }
}


// 下拉刷新处理
const onRefresh = () => {
  getStoreList(false)
}

// 上拉加载更多处理
onReachBottom(() => {
  if (loadStatus.value === 'loadmore') {
    getStoreList(true)
  }
})

// 页面滚动处理（用于下拉刷新）
onPageScroll((e) => {
  scrollTop.value = e.scrollTop
  // 传递滚动事件给下拉刷新组件
  if (pullDownRefresh.value) {
    pullDownRefresh.value.onScroll(e)
  }
})
// #endregion·


// 距离
const getDistance = (distance: number) => {
  if(distance){

    return distance < 1 ? `${distance}米` : `${distance}km`
  }else{
    return ''
  }

}


 

//点击去加油
const handleGoBuy = (item: any) => {
  console.log('点击了去加油', item)
  oilStore.addOil({ ...item, distance: getDistance(item.distance) })
  if (isApp.value) {
    uni.navigateTo({ url: `/pages/refuel/refuelBuy?from=app` })
  } else {
    uni.navigateTo({ url: `/pages/refuel/refuelBuy` })
  }
}
//返回顶部,所在的父盒子不能设置高度
onPageScroll((e: any) => {
  scrollTop.value = e.scrollTop
})

// #region ************************* 地图操作 ********* /
const gotoAddress = (item: any) => {
  clickObj.value = {
    latitude: item.latitude,
    longitude: item.longitude,
    address: item.address,
    name: item.stationName
  }
  showMap.value = true
}

//高德
const openGMap = () => {
  const { latitude, longitude, name } = clickObj.value
  window.location.href = `https://uri.amap.com/marker?position=${longitude},${latitude}&name=${name}&coordinate=gaode&callnative=0`
}
//百度
const openBMap = () => {
  const { latitude, longitude, name } = clickObj.value
  window.location.href = `http://api.map.baidu.com/marker?location=${latitude},${longitude}&title=${name}&output=html`
}
// 腾讯
const openTMap = () => {
  const { latitude, longitude, name } = clickObj.value
  window.location.href = `https://apis.map.qq.com/uri/v1/marker?marker=coord:${latitude},${longitude};title=${name}`
}
// 复制地址
const copyMap = () => {
  const address = clickObj.value.address
    ? clickObj.value.address
    : '地址信息不可用' // 获取地址信息，若无则显示默认文本
  uni.setClipboardData({
    data: address,
    success: () => {
      showMap.value = false
      uni.showToast({
        title: '复制成功'
      })
    },
    fail: () => {
      showMap.value = false
      uni.showToast({
        title: '复制失败',
        icon: 'none'
      })
    }
  })
}

// #endregion

// 上拉触底加载更多
onReachBottom(() => {
  if (loadStatus.value === 'loadmore') {
    getStoreList(true)
  }
})

onLoad(async (option: any) => {
  // app/ios
  if (option?.from && option.from.toLowerCase() === 'app') {
    isApp.value = true
    uni.setStorageSync('from', isApp.value)
    // #ifdef H5
    // @ts-ignore
    window.JSBridge.registerEvent('HYUserEvent', async (data) => {
      console.log('收到 App 用户信息:', data)
      const result = await getLocationInfo()
      console.log('appresult经纬度==》', result);
      
      location.value = result.location
      // 只有当location有数据时才调用getStoreList
      if (location.value) {
        await enumOliList()
        await enumBrandList()
        await getStoreList()
      }
    })
    // #endif
  } else {
    //h5
    const result = await getLocationInfo()
    console.log('h5result经纬度==》', result);

    location.value = result.location
    // 只有当location有数据时才调用getStoreList
    if (location.value) {
      await enumOliList()
      await enumBrandList()
      await getStoreList()
    }
  }
})

</script>
<style lang="scss" scoped>
.bigbox {
  font-size: 24rpx;
  background: linear-gradient(
    to bottom,
    #f9dcb8 5%,
    #faead7 25%,
    #f5ece0 55%,
    #f8f8f8 85%,
    #f5f5f5 100%
  );
  width: 100%; /* 改为100%而不是固定750rpx */
  overflow-x: hidden; /* 防止横向滚动 */

  .top {
    .bjbox {
      display: flex;
      justify-content: space-between;
      align-items: center;
      padding: 20rpx;
      width: 100%;
      box-sizing: border-box;
      .search-container {
        flex: 1;
        margin-right: 20rpx;
      }

      .reload-icon {
        flex-shrink: 0;
      }
    }

    .sxbox {
      margin: 0 20rpx;
      width: auto; /* 改为auto */
      display: flex;
      align-items: center;
      justify-content: space-around;
      background-color: #fff;
      .kuai {
        font-size: 28rpx;
        cursor: pointer;
        width: 150rpx;
        flex-shrink: 0; /* 防止压缩 */
      }
      .dropdown {
        flex: 1;
        overflow: hidden; /* 防止下拉菜单溢出 */
      }
    }
  }

  .footer {
    padding: 20rpx;
    width: 100%; /* 改为100% */
    box-sizing: border-box; /* 包含padding在内 */

    .xhz {
      width: 100%;
      background-color: #fff;
      border-radius: 10rpx;
      padding: 20rpx;
      margin-bottom: 20rpx;
      box-sizing: border-box; /* 包含padding在内 */

      .xhz-l {
        width: 100%;
        .head {
          display: flex;
          align-items: center;
          justify-content: space-between;
        }

        .textBox {
          margin: 20rpx 0;
          display: flex;
          justify-content: space-between;
          align-items: center;

          .left {
            flex-wrap: wrap;
            width: auto; /* 不固定宽度 */
            flex: 1; /* 占据剩余空间 */
          }

          .right {
            display: flex;
            align-items: center;
            gap: 10rpx;
            font-size: 26rpx;
            color: #999;
            flex-shrink: 0; /* 防止压缩 */
            white-space: nowrap; /* 防止换行 */

            .van-icon {
              margin-right: 5rpx;
            }
          }
        }
      }
    }
  }
}
.address-text {
  margin: 10rpx 0 10rpx 60rpx;
  width: auto;
  max-width: 320rpx;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}
.overwz {
  //   单行文本省略号
  width: 100%;
  white-space: nowrap; /* 禁止文本换行 */
  overflow: hidden; /* 隐藏溢出内容 */
  text-overflow: ellipsis; /* 用省略号表示被截断的文本 */
}
.btwz {
  font-weight: bold;
  font-size: 30rpx;
}

.active {
  color: #ff6c18 !important;
}

.jgwz {
  color: #fd6135;
  font-weight: bold;
  .quan1 {
    margin-left: 20rpx;
    padding: 6rpx;
    color: #fff;
    background-color: #ff4600;
  }
  .quan2 {
    padding: 6rpx;
    background-color: #ffece1;
  }
}
.txbox {
  display: flex;
  align-items: center;
  font-size: 28rpx;
}
.mapbox {
  display: flex;
  flex-direction: column;
  align-items: center;
  background-color: #f7f8fa;

  .btn {
    width: 100%;
    height: 80rpx;
    border: none;
    background-color: #fff;
  }

  .btn2 {
    margin-top: 20rpx;
  }
}
//修改下拉框遮罩层的高度
::v-deep .u-dropdown__content__mask {
  height: 50vh !important; /* 设置遮罩层高度为视口高度的50% */
  max-height: 50vh !important;
}
:deep(.bjbox.u-search.u-content) {
  background-color: #fff !important;
}
:deep(.van-dropdown-menu__bar) {
  --van-dropdown-menu-shadow: none !important;
  box-shadow: none !important;
  background-color: transparent !important;
}
</style>
